<?php

namespace Jobs\Daemon\Netease;

/**
 * @name 时长结算
 * Class CallTime
 * @package Jobs\Daemon\Netease
 */
class CallTime extends \S\Thread\Worker {
    protected $whileSleep = 0;

    public function process() {
        try {
            $data = (new \Dao\Queue\Netease())->popTime();
            if ($data) {
                //已存在的数据不在处理
                $info = (new \Data\Netease\Callback())->get($data['id']);
                if (!$info) {
                    //回调消息入库
                    (new \Data\Netease\Callback())->add($data);
                    //解析消息体
                    $msg = json_decode($data['msg'], true);
                    $channel_id = $msg['channelId'];
                    $mem_info = json_decode($msg['members'], true);
                    //获取发起者的消耗时长
                    $duration = '';
                    foreach ($mem_info as $item) {
                        if ($item['caller']) {
                            $duration = $item['duration'];
                        }
                    }
                    //订单号
                    $ext_info = json_decode($msg['ext'],true);
                    $cid = $ext_info['cid'];
                    //业务通知：白板类型的回调不进行结算通知
                    if ($msg['type'] == 'VEDIO' || $msg['type'] == 'AUDIO') {
                        //如果消息过近就延迟一分钟
                        if((time()*1000 - $data['curtime']) < 60 * 1000 ){
                            sleep(120);
                        }
                        (new \Service\Consume\Consume())->done($cid, $channel_id, $duration);
                    }
                    //结算消息记录
                    $time_info['msg_id'] = $data['id'];
                    $time_info['channel_id'] = $msg['channelId'];
                    $time_info['duration'] = $msg['duration'];
                    $time_info['create_time'] = $msg['createtime'];
                    $time_info['live'] = $msg['live']?:'';
                    $time_info['members'] = $msg['members'];
                    $time_info['status'] = $msg['status'];
                    $time_info['type'] = $msg['type'];
                    $time_info['ext'] = $msg['ext']?:'';
                    $time_info['running'] = $msg['running'] ?:'';
                    (new \Data\Netease\Time())->add($time_info);
                    //如果是超长通知直接关闭
                    if($time_info['running']){
                        (new \Data\Netease\Room())->close($time_info['channel_id']);
                        \S\Log\Logger::getInstance()->warning(array('超长通话',json_encode($time_info)));
                    }
                }
            } else {
                sleep(5);
            }
        } catch (\Exception $e) {
            \S\Log\Logger::getInstance()->warning(array('错误码:' . $e->getCode(), '错误信息:' . $e->getMessage(), json_encode($data)));
        }
    }
}